package com.shanghaionstar.weight;

import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shanghaionstar.R;

/**
 * Created by Yonglang Hong on 2016/11/21.
 */
public class ToastView {

    public static final String TAG = ToastView.class.getSimpleName();

    public static void showToast(RelativeLayout parent, @StringRes int resId){
        showToast(parent,parent.getResources().getString(resId));
    }

    public static void showToast(RelativeLayout parent, String str){
        TextView tv = new TextView(parent.getContext());
        tv.setBackgroundResource(R.color.alpha_blue);
        tv.setTextColor(ContextCompat.getColor(parent.getContext(),R.color.white));
        tv.setText(str);
        tv.setTag(TAG);
        int paddingSize = parent.getResources().getDimensionPixelSize(R.dimen.dp_10);
        tv.setPadding(0,paddingSize,0,paddingSize);
        tv.setGravity(Gravity.CENTER);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        tv.setLayoutParams(layoutParams);
        if (parent.getTag() != null
                && parent.getTag() instanceof TextView
                && TAG.equalsIgnoreCase(((TextView)parent.getTag()).getTag().toString()))
            return;
        parent.setTag(tv);
        parent.addView(tv);
    }

    public static void hideToast(RelativeLayout parent){
        if (parent.getTag() != null
                && parent.getTag() instanceof TextView) {
            if (TAG.equalsIgnoreCase(((TextView)parent.getTag()).getTag().toString())){
                parent.removeView((TextView)parent.getTag());
                parent.setTag(null);
            }
        }
    }
}
